package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;


@Controller
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;
    
    @Autowired
    private StudentService studentService;

    @RequestMapping("student")
    public String getsStudent(ModelMap map,Student student){
        if (StringUtils.isEmpty(student.getAge())){
            student.setAge(null);
        }
        if (StringUtils.isEmpty(student.getName())){
            student.setName(null);
        }
        map.put("s", studentService.getAll(student));
        return "list";
    }
    @RequestMapping("student/delete/{id}")
    public String delete(@PathVariable Long id){
        studentService.delete(id);
        return "redirect:/student";
    }
    @RequestMapping("student/create")
    public String create(){
        return "create";
    }

    @RequestMapping("student/save")
    public String save(@RequestParam String name,@RequestParam String age){
        Student s = new Student();
        s.setAge(age);
        s.setName(name);
        studentService.save(s);
        return "redirect:/student";
    }
    @RequestMapping("student/update/{id}")
    public String update(ModelMap map,@PathVariable Long id){
        map.put("student", studentService.get(id));
        return "update";
    }

    @RequestMapping("student/edit")
    public String edit(Student st){
        studentService.save(st);
        return "redirect:/student";
    }
}
